import React, { useRef, useEffect, useState } from 'react';
import { formatTime } from '../utils/lrcParser';
import './AudioPlayer.css';

export type PlayMode = 'normal' | 'repeat-one' | 'repeat-sentence';

interface AudioPlayerProps {
  audioUrl: string;
  currentTime: number;
  duration: number;
  isPlaying: boolean;
  playMode: PlayMode;
  playbackRate?: number;
  onTimeUpdate: (time: number) => void;
  onDurationChange: (duration: number) => void;
  onPlay: () => void;
  onPause: () => void;
  onSeek: (time: number) => void;
  onPlayModeChange: (mode: PlayMode) => void;
  onPlaybackRateChange?: (rate: number) => void;
  sentenceStartTime?: number;
  sentenceEndTime?: number;
}

const AudioPlayer: React.FC<AudioPlayerProps> = ({
  audioUrl,
  currentTime,
  duration,
  isPlaying,
  playMode,
  playbackRate = 1,
  onTimeUpdate,
  onDurationChange,
  onPlay,
  onPause,
  onSeek,
  onPlayModeChange,
  onPlaybackRateChange,
  sentenceStartTime,
  sentenceEndTime
}) => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    const handleTimeUpdate = () => {
      const time = audio.currentTime;
      onTimeUpdate(time);

      // 句子重复模式
      if (playMode === 'repeat-sentence' && 
          sentenceEndTime && 
          time >= sentenceEndTime) {
        if (sentenceStartTime !== undefined) {
          audio.currentTime = sentenceStartTime;
        }
      }
    };

    const handleDurationChange = () => {
      onDurationChange(audio.duration || 0);
    };

    const handleLoadStart = () => setIsLoading(true);
    const handleCanPlay = () => setIsLoading(false);

    const handleEnded = () => {
      if (playMode === 'repeat-one') {
        audio.currentTime = 0;
        audio.play();
      } else {
        onPause();
      }
    };

    audio.addEventListener('timeupdate', handleTimeUpdate);
    audio.addEventListener('durationchange', handleDurationChange);
    audio.addEventListener('loadstart', handleLoadStart);
    audio.addEventListener('canplay', handleCanPlay);
    audio.addEventListener('ended', handleEnded);

    return () => {
      audio.removeEventListener('timeupdate', handleTimeUpdate);
      audio.removeEventListener('durationchange', handleDurationChange);
      audio.removeEventListener('loadstart', handleLoadStart);
      audio.removeEventListener('canplay', handleCanPlay);
      audio.removeEventListener('ended', handleEnded);
    };
  }, [playMode, sentenceStartTime, sentenceEndTime, onTimeUpdate, onDurationChange, onPause]);

  // 设置播放速度
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    
    audio.playbackRate = playbackRate;
  }, [playbackRate]);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    if (isPlaying) {
      audio.play().catch(console.error);
    } else {
      audio.pause();
    }
  }, [isPlaying]);

  // 同步currentTime prop到audio元素
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    // 只有当差异超过0.1秒时才同步，避免频繁更新
    const timeDiff = Math.abs(audio.currentTime - currentTime);
    if (timeDiff > 0.1) {
      audio.currentTime = currentTime;
    }
  }, [currentTime]);

  const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const progressBar = e.currentTarget;
    const rect = progressBar.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const percentage = clickX / rect.width;
    const newTime = percentage * duration;
    onSeek(newTime);
  };

  const getPlayModeIcon = () => {
    switch (playMode) {
      case 'repeat-one':
        return '🔂';
      case 'repeat-sentence':
        return '🔁';
      default:
        return '▶️';
    }
  };

  const getPlayModeText = () => {
    switch (playMode) {
      case 'repeat-one':
        return '单曲循环';
      case 'repeat-sentence':
        return '句子重复';
      default:
        return '顺序播放';
    }
  };

  const cyclePlayMode = () => {
    const modes: PlayMode[] = ['normal', 'repeat-one', 'repeat-sentence'];
    const currentIndex = modes.indexOf(playMode);
    const nextIndex = (currentIndex + 1) % modes.length;
    onPlayModeChange(modes[nextIndex]);
  };

  const progressPercentage = duration > 0 ? (currentTime / duration) * 100 : 0;

  return (
    <div className="audio-player">
      <audio
        ref={audioRef}
        src={audioUrl}
        preload="metadata"
      />
      
      <div className="player-controls">
        <button
          className="btn btn-primary play-btn"
          onClick={isPlaying ? onPause : onPlay}
          disabled={isLoading}
        >
          {isLoading ? '⏳' : isPlaying ? '⏸️' : '▶️'}
        </button>

        <div className="time-info">
          <span>{formatTime(currentTime)}</span>
          <span>/</span>
          <span>{formatTime(duration)}</span>
        </div>

        <button
          className="btn btn-secondary mode-btn"
          onClick={cyclePlayMode}
          title={getPlayModeText()}
        >
          {getPlayModeIcon()}
          <span className="mode-text">{getPlayModeText()}</span>
        </button>

        {onPlaybackRateChange && (
          <div className="speed-control">
            <label htmlFor="speed-select">速度:</label>
            <select
              id="speed-select"
              value={playbackRate}
              onChange={(e) => onPlaybackRateChange(parseFloat(e.target.value))}
              className="speed-select"
            >
              <option value={0.5}>0.5x</option>
              <option value={0.75}>0.75x</option>
              <option value={1}>1x</option>
              <option value={1.25}>1.25x</option>
              <option value={1.5}>1.5x</option>
              <option value={2}>2x</option>
            </select>
          </div>
        )}
      </div>

      <div className="progress-container">
        <div 
          className="progress-bar"
          onClick={handleProgressClick}
        >
          <div 
            className="progress-fill"
            style={{ width: `${progressPercentage}%` }}
          />
          <div 
            className="progress-thumb"
            style={{ left: `${progressPercentage}%` }}
          />
        </div>
      </div>

      {playMode === 'repeat-sentence' && sentenceStartTime !== undefined && sentenceEndTime && (
        <div className="sentence-info">
          <span>重复片段: {formatTime(sentenceStartTime)} - {formatTime(sentenceEndTime)}</span>
        </div>
      )}
    </div>
  );
};

export default AudioPlayer;